package Others.SimpleCalculator;

import Others.SimpleCalculator.entity.*;
import cn.hutool.core.bean.BeanUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        run();
    }

    private static void run() {
        //计算器使用次数
        int count = 1;
        //界面重置控制器--每输入错误达到N的倍数就进行界面的调用
        int i = 1;
        //控制输入计算数字的顺序
        int j = 1;
        //控制操作输入--是否向下进行
        boolean operatorFlag = true;
        //操作符序号
        String operator = "";
        //收集计算的数字
        List<Double> arr = new ArrayList<>();
        //操作符限定
        String[] operators = {"1", "2", "3", "4", "5", "6"};//有哪些操作,在这里限定死先--后续在优化
        //计算历史记录
        List<String> history = new ArrayList<>();
        //Scanner输入对象创建
        Scanner scanner = new Scanner(System.in);
        //计算器逻辑核心
        core(operatorFlag, i, operator, scanner, history, operators, j, arr, count);
    }

    private static void core(boolean operatorFlag, int i, String operator, Scanner scanner, List<String> history, String[] operators, int j, List<Double> arr, int count) {
        //这里使用了标签--来决定跳出哪一个循环
        R1:
        while (true) {
            //展示菜单
            showMenu();
            //输入操作符
            while (operatorFlag) {
                if (i % 3 == 0)
                    showMenu();
                System.out.println("请选择您的操作：");
                operator = scanner.nextLine();
                if (operator.equals("5"))
                    break R1;
                if (operator.equals("6")) {
                    // 显示历史记录
                    showHistory(history);
                    i++;
                    continue;
                }
                if (Arrays.asList(operators).contains(operator))
                    operatorFlag = false;
                else {
                    System.out.println("您选择的操作错误！请输入1-6之间的数字。");
                    i++;
                }
            }
            //重置操作输入
            operatorFlag = true;
            //重置界面刷新
            i = 1;
            System.out.println("第一个数字将会被作为计算的基数");
            //输入数字
            numInput(scanner, j, arr);
            //重置数字顺序
            j = 1;
            //数组为空,返回菜单
            if (arr.isEmpty()) {
                System.out.println("未输入任何数字，返回主菜单。");
                count++;
                continue;
            }
            //计算结果
            calculateRes(operator, history, arr, count);
            //重置计算内容
            arr.clear();
            //计算器使用次数加一
            count++;
            scanner.nextLine();//这里对操作的暂存区进行了刷新
        }
    }

    private static void calculateRes(String operator, List<String> history, List<Double> arr, int count) {
        if (arr.size() == 1) {
            System.out.println("只输入了一个数字，结果为：" + arr.get(0));
            history.add("第" + count + "次计算: 只输入了一个数字 " + arr.get(0));
        } else {
            //操作 选择其他 也返回0
            String operation = getOperationName(operator);
            double result = calculate(operation, arr);
            System.out.println("计算中...结果为：" + result);
            //保存到历史记录
            saveHis(history, arr, count, operation, result);
        }
    }

    private static void saveHis(List<String> history, List<Double> arr, int count, String operation, double result) {
        StringBuilder historyEntry = new StringBuilder("第" + count + "次计算: ");
        for (int k = 0; k < arr.size(); k++) {
            if (k > 0) {
                historyEntry.append(" ").append(operation).append(" ");
            }
            historyEntry.append(arr.get(k));
        }
        historyEntry.append(" = ").append(result);
        history.add(historyEntry.toString());
    }

    private static void numInput(Scanner scanner, int j, List<Double> arr) {
        double num;
        while (true) {
            try {
                System.out.println("请输入第" + j + "个数字 (输入0表示结束输入): ");
                num = scanner.nextDouble();
                if (num == 0) {
                    System.out.println("输入结束，开始计算...");
                    break;
                }
                arr.add(num);
                j++;
            } catch (Exception e) {
                scanner.nextLine(); //清除无效输入
                System.out.println("输入错误！请重新输入数字。");
            }
        }
    }

    private static void showMenu() {
        System.out.println("\n========== 简单计算器 ==========");
        System.out.println("1. 加法 (+)");
        System.out.println("2. 减法 (-)");
        System.out.println("3. 乘法 (*)");
        System.out.println("4. 除法 (/)");
        System.out.println("5. 退出程序");
        System.out.println("6. 查看历史记录");
        System.out.println("================================");
    }

    private static void showHistory(List<String> history) {
        System.out.println("\n========== 计算历史记录 ==========");
        if (history.isEmpty()) {
            System.out.println("暂无计算历史记录");
        } else {
            for (int i = 0; i < history.size(); i++) {
                System.out.println((i + 1) + ". " + history.get(i));
            }
        }
        System.out.println("================================");
    }

    private static String getOperationName(String operator) {
        return switch (operator) {
            case "1" -> "+";
            case "2" -> "-";
            case "3" -> "*";
            case "4" -> "/";
            default -> "";
        };
    }

    private static double calculate(String operator, List<Double> a) {
        double number = a.get(0);
        CalculateInterface calculateInterfaceBean = CalculateInterfaceFactory.getCalculateInterfaceBean(operator);
        return calculateInterfaceBean == null ? 0 : calculateInterfaceBean.calculate(number, a);

        //这里有原来的switch 语句，后改成了工厂模式，后续修改，只需要改工厂内容即可
//        switch (operator) {
//            case "1":
//                return new Plus().Calculate(number, a);
//            case "2":
//                return new Minus().Calculate(number, a);
//            case "3":
//                return new Multiply().Calculate(number, a);
//            case "4":
//                return new Division().Calculate(number, a);
//            default:
//                return 0;//这里保底
//        }

    }

}